import axios from './axios'
import { Message } from 'element-ui'
let http = 'http://localhost:3000/'
export function get(url, params = {}, config = {}, cb) {
  return new Promise((resolve, reject) => {
    axios
      .get(http + url, {
        params,
        ...config
      })
      .then(rsp => resolve(rsp))
      .catch(e => {
        if (cb && typeof cb === 'function') {
          cb()
          return
        }
        handleError(e)
        reject(e)
      })
  })
  // return axios.get(url, {
  //   params,
  //   ...config
  // })
}

export function post(url, params = {}, config = {}, cb) {
  return new Promise((resolve, reject) => {
    axios
      .post(http + url, params, config)
      .then(rsp => resolve(rsp))
      .catch(e => {
        if (cb && typeof cb === 'function') {
          cb()
          return
        }
        handleError(e)
        reject(e)
      })
  })
}
// 全局ajax错误回调
export function handleError(e) {
  let str = e + ''

  if (e.toString() === 'Cancel') {
    console.log('取消了axios请求！')
    return
  }
  let msg = `请求无响应，请稍后再试`
  if (str.search('timeout') !== -1) {
    // 超时error捕
    msg = '请求超时，请稍后再试'
  } else if (~str.search('Network Error')) {
    msg = '请检查您的网络'
  }
  if (e.response && e.response.data) {
    let reg = /<body>[\S\s]*?<\/pre>/
    let htmlReg = /<[\S\s]+?>/g
    let showErr = e.response.data.match(reg) || [str]
    let errMsg = showErr[0]
      .replace(htmlReg, '')
      .replace(/[\n\t\f]+/g, '<br>')
      .replace(/^<br>/, '')
    msg += `<br>${errMsg}`
  }
  Message({
    message: msg,
    dangerouslyUseHTMLString: true,
    type: 'error'
  })
  // window.eventBus.$emit('hideLoading')
}